/** 
 *	isEmpty, 						判断是否为空
 *	isEmptyToast, 			判断数据是否为空 并弹窗提示
 *	verifyTelPhone, 		验证手机号
 *	verifyCode,					验证验证码
 *	verifyPassword, 		验证密码
 *	verifyName, 				验证姓名
 *	verifyLength, 			验证数据长度
 *	toast, 							弹窗
 *	verifyIDcard, 			验证身份证
 *	unique, 						数组去重
 *	ArrayIsEqual, 			比较数组是否相等
 *	dateFormat, 				时间戳转日期
 *	mpGetUserProfile, 	微信小程序获取用户信息
 *	mpGetCode, 					微信小程序获取code
 *	wechatMpPay, 				微信小程序支付
 *	prePageData, 				获取上页数据
 *	to, 								跳转页面
 *	getDate, 						获取当前时间或几天后的时间
 *	getDaysBetween, 		获取两个日期间隔时间
 *	makePhone, 					拨打电话
 *	getdiffdate, 				获取两个日期之间的所有日期组合
 *	previewImg, 				预览图片
 *	openMap, 						打开地图导航
 *	randomArray, 				数组随机打乱
 */

/**
 *	@function 判断数据是否为空
 *	@param 		{Number,String,Object} 		判断数据	 require
 *	@param 		{desc}		弹窗文字
 *	@return 	{Boolean}	true:不为空 false:为空
 */

const isEmpty = (obj, desc) => {
	if (typeof obj === "undefined" || obj === null || obj === "" || obj === false) {
		if (desc) {
			toast(desc)
		}
		return false;
	} else {
		return true;
	}
}

// 判断数据是否为空 并弹窗提示
const isEmptyToast = (array) => {
	array.some(item => {
		if (typeof item.data == "undefined" || item.data == null || item.data == "") {
			toast(item.title)
			return false;
		} else {
			return true;
		}
	})
}

/**
 *	@function 验证手机号
 *	@param 		{Number,String} 	判断数据	 require
 *	@return 	{Boolean}	
 */

const verifyTelPhone = (param) => {
	if (param == '') {
		toast('请输入手机号码')
		return false
	} else if (!(/^1[3456789]\d{9}$/.test(param))) {
		toast('请输入正确的手机号码')
		return false
	} else {
		return true
	}
}

/**
 *	@function 验证验证码号
 *	@description 判断数据是否为6位数
 *	@param 		{Number,String} 	判断数据	 require
 *	@return 	{Boolean}	
 */
const verifyCode = (param) => {
	if (param == '' || param.length != 6) {
		toast('请输入正确的验证码')
		return false
	} else {
		return true
	}
}

/**
 *	@function 验证密码
 *	@description 验证密码是否为6-12位数
 *	@param 		{String} 	判断数据	 require
 *	@return 	{Boolean}	
 */

const verifyPassword = (param) => {
	if (param.length < 6 || param.length > 12) {
		toast('请输入6-12位密码')
		return false
	} else {
		return true
	}
}

/**
 *	@function 验证姓名
 *	@description 验证姓名是否为2-5个字符
 *	@param 		{String} 	判断数据	 require
 *	@return 	{Boolean}	
 */
const verifyName = (param) => {
	if (param.length < 2) {
		toast('名字不能少于2个字')
		return false
	} else if (param.length > 5) {
		toast('名字不能超过5个字')
		return false
	} else {
		return true
	}
}

/**
 *	@function 验证数据长度
 *	@description 验证
 *	@param 	{String,Number}	判断数据	 require  
 *	@param 	{Number} 				最小长度	 require  
 *	@param 	{Number} 				最大长度	 require
 *	@return {Boolean}	
 */
const verifyLength = (param, number1, number2) => {
	if (param.length >= number1 && param.length <= number2) {
		return false
	} else {
		return true
	}
}


/**
 *	@function 		弹窗提示
 *	@description 	弹窗提示 图标样式	默认为空
 *	@param 				{String} 	弹窗文字	 require
 */
const toast = (title, icon) => {
	uni.showToast({
		title,
		icon: icon || 'none'
	})
}

/**
 *	@function 		身份证验证
 *	@description 	身份证验证
 *	@param 				{String} 	身份证号	 require
 *	@return 			{Boolean}	
 */
const verifyIDcard = code => {
	var city = {
		11: "北京",
		12: "天津",
		13: "河北",
		14: "山西",
		15: "内蒙古",
		21: "辽宁",
		22: "吉林",
		23: "黑龙江 ",
		31: "上海",
		32: "江苏",
		33: "浙江",
		34: "安徽",
		35: "福建",
		36: "江西",
		37: "山东",
		41: "河南",
		42: "湖北 ",
		43: "湖南",
		44: "广东",
		45: "广西",
		46: "海南",
		50: "重庆",
		51: "四川",
		52: "贵州",
		53: "云南",
		54: "西藏 ",
		61: "陕西",
		62: "甘肃",
		63: "青海",
		64: "宁夏",
		65: "新疆",
		71: "台湾",
		81: "香港",
		82: "澳门",
		91: "国外 "
	};
	var tip = "";
	var pass = true;
	if (!code || !/^\d{6}(18|19|20)?\d{2}(0[1-9]|1[012])(0[1-9]|[12]\d|3[01])\d{3}(\d|X)$/i.test(code)) {
		tip = "身份证号格式错误";
		pass = false;
	} else if (!city[code.substr(0, 2)]) {
		tip = "地址编码错误";
		pass = false;
	} else {
		//18位身份证需要验证最后一位校验位
		if (code.length == 18) {
			code = code.split('');
			//∑(ai×Wi)(mod 11)
			//加权因子
			var factor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
			//校验位
			var parity = [1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2];
			var sum = 0;
			var ai = 0;
			var wi = 0;
			for (var i = 0; i < 17; i++) {
				ai = code[i];
				wi = factor[i];
				sum += ai * wi;
			}
			var last = parity[sum % 11];
			if (parity[sum % 11] != code[17]) {
				tip = "校验位错误";
				pass = false;
			}
		}
	}
	return pass;
}

/**
 *	@function 		数组去重
 *	@description 	数组去重
 *	@param 				{Array} 	数组	 require
 *	@return 			{Array}		数组
 */
const unique = data => {
	return Array.from(new Set(data))
}

/**
 *	@function 		获取用户信息
 *	@description 	微信小程序获取用户信息
 *	@return 			{Object}	用户信息
 */
const mpGetUserProfile = () => {
	return new Promise((resolve, reject) => {
		try {
			uni.getUserProfile({
				lang: 'zh_CN',
				desc: '获取用户信息',
				success: userInfo => {
					console.log(userInfo, 'userInfo');
					resolve(userInfo)
				},
				fail: err => {
					console.log(err, 'err')
					reject(err)
				}
			});
		} catch (e) {
			console.log('catch', e)
		}
	})
}

/**
 *	@function 		获取用户code
 *	@description 	微信小程序获取code
 *	@return 			{Object}	用户信息
 */
const mpGetCode = data => {
	return new Promise((resolve, reject) => {
		try {
			uni.login({
				provider: 'weixin',
				success: res => {
					console.log('code', 'res');
					resolve(res)
				},
				fail: err => {
					console.log(err, 'err')
					reject(err)
				}
			});
		} catch (e) {
			console.log('catch', e)
		}
	})
}

/**
 *	@function 		验证两个数组是否完全相等
 *	@description 	验证两个数组是否完全相等
 *	@param 				{Array}  需要验证的数组1 require
 *	@param 				{Array}  需要验证的数组2	 require
 *	@return 			{Boolean}	
 */
const ArrayIsEqual = (arr1, arr2) => {
	if (arr1 === arr2) { //如果2个数组对应的指针相同，那么肯定相等，同时也对比一下类型
		return true;
	} else {
		if (arr1.length != arr2.length) {
			return false;
		} else { //长度相同
			for (let i in arr1) { //循环遍历对比每个位置的元素
				if (arr1[i] != arr2[i]) { //只要出现一次不相等，那么2个数组就不相等
					return false;
				}
			} //for循环完成，没有出现不相等的情况，那么2个数组相等
			return true;
		}
	}

}
/**
 *	@function 		微信小程序支付
 *	@description 	微信小程序支付
 *	@param 				{Object}  统一下单数据
 *	@return 			{Object}	支付信息
 */
const wechatMpPay = data => {
	return new Promise((resolve, reject) => {
		try {
			uni.requestPayment({
				provider: 'wxpay',
				timeStamp: data.timeStamp.toString(),
				nonceStr: data.nonceStr,
				package: data.package,
				signType: data.signType,
				paySign: data.paySign,
				success: (res) => {
					console.log(res)
					resolve(res)
				},
				fail: (err) => {
					console.log(err)
					resolve(err)
				}
			})
		} catch (e) {
			console.log('catch', e)
		}
	})
}

const dateFormat = (date, format) => {
	var time = new Date(date * 1000);
	var y = time.getFullYear();
	var month = time.getMonth() + 1;
	var d = time.getDate();
	var h = time.getHours();
	var m = time.getMinutes();
	var s = time.getSeconds();
	month = month < 10 ? ('0' + month) : month;
	m = m < 10 ? ('0' + m) : m;
	d = d < 10 ? ('0' + d) : d;
	s = s < 10 ? ('0' + s) : s;
	if (format == 'y-m') {
		return `${y}年${month}月`
	} else if (format == 'y-m-d') {
		return `${y}-${month}-${d}`
	} else {
		return `${y}-${month}-${d} ${h}:${m}:${s}`
	}
}

// 获取上页数据
const prePageData = () => {
	let pages = getCurrentPages();
	let prePage = pages[pages.length - 2];
	return prePage.$vm;
}

// 跳转页面
const to = (url) => {
	uni.navigateTo({
		url,
		fail: () => {
			uni.switchTab({
				url
			})
		}
	})
}

/**
 * 获取任意时间
 */
const getDate = (date, AddDayCount = 0) => {
	if (!date) {
		date = new Date();
	}
	if (typeof date !== 'object') {
		date = date.replace(/-/g, '/');
	}
	const dd = new Date(date);

	dd.setDate(dd.getDate() + AddDayCount); // 获取AddDayCount天后的日期

	const y = dd.getFullYear();
	const m = dd.getMonth() + 1; // 获取当前月份的日期，不足10补0
	const d = dd.getDate(); // 获取当前几号，不足10补0
	return {
		fullDate: y + '-' + m + '-' + d,
		year: y,
		month: m,
		date: d,
		day: dd.getDay()
	};
}

/**
 * 获取两个日期间隔时间
 */

const getDaysBetween = (startDate, enDate) => {
	const sDate = Date.parse(startDate)
	const eDate = Date.parse(enDate)
	if (sDate > eDate) {
		return 0
	}
	if (sDate === eDate) {
		return 1
	}
	const days = (eDate - sDate) / (1 * 24 * 60 * 60 * 1000)
	return days
}

// 拨打电话
const makePhone = (number) => {
	uni.makePhoneCall({
		phoneNumber: number,
		fail() {
			uni.showToast({
				icon: "error",
				title: '拨打电话失败'
			})
		}
	})
}

const getdiffdate = (stime, etime) => { //获取两个日期中间的日期
	//初始化日期列表，数组
	var diffdate = new Array();
	var i = 0;
	//开始日期小于等于结束日期,并循环
	while (stime <= etime) {
		diffdate[i] = stime;

		//获取开始日期时间戳
		var stime_ts = new Date(stime).getTime();
		console.log('当前日期：' + stime + '当前时间戳：' + stime_ts);

		//增加一天时间戳后的日期
		var next_date = stime_ts + (24 * 60 * 60 * 1000);

		//拼接年月日，这里的月份会返回（0-11），所以要+1
		var next_dates_y = new Date(next_date).getFullYear() + '-';
		var next_dates_m = (new Date(next_date).getMonth() + 1 < 10) ? '0' + (new Date(next_date).getMonth() + 1) +
			'-' : (new Date(next_date).getMonth() + 1) + '-';
		var next_dates_d = (new Date(next_date).getDate() < 10) ? '0' + new Date(next_date).getDate() : new Date(
			next_date).getDate();

		stime = next_dates_y + next_dates_m + next_dates_d;

		//增加数组key
		i++;
	}
	return diffdate;
}
// 预览图片
const previewImg = (urls, current) => {
	uni.previewImage({
		urls,
		current
	})
}
// 打开地图导航
const openMap = (longitude, latitude) => {
	console.log(longitude)
	console.log(latitude)
	uni.openLocation({
		longitude: parseFloat(longitude),
		latitude: parseFloat(latitude),
	})
}

// 数组随机打乱
const randomArray = (arr) => {
	for (let i = 0, len = arr.length; i < len; i++) {
		let index = parseInt(Math.random() * (len - 1));
		let tempValue = arr[i];
		arr[i] = arr[index];
		arr[index] = tempValue;
	}
	return arr;
}

export default {
	isEmpty,
	isEmptyToast,
	verifyTelPhone,
	verifyCode,
	verifyPassword,
	verifyName,
	verifyLength,
	toast,
	verifyIDcard,
	unique,
	mpGetUserProfile,
	mpGetCode,
	ArrayIsEqual,
	dateFormat,
	wechatMpPay,
	prePageData,
	to,
	getDate,
	getDaysBetween,
	makePhone,
	getdiffdate,
	previewImg,
	openMap,
	randomArray,
}
